package com.vercon.moensmart.utils;

import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.session.MediaController;
import android.media.session.MediaSessionManager;
import android.media.session.PlaybackState;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;

import androidx.fragment.app.FragmentActivity;

import com.vercon.common.utils.LogUtils;
import com.vercon.common.utils.ThreadUtil;
import com.vercon.moensmart.MainApplication;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by csh on 2021/11/26
 */
public class AppUtil {

    private static final int WINDOWING_MODE_FREEFORM = 5;

    /**
     * 打开指定包名的APP
     *
     * @param context
     * @param packageName
     */
    public static void openOtherApp(Context context, String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            Intent launchIntentForPackage = manager.getLaunchIntentForPackage(packageName);
            if (launchIntentForPackage != null) {
                MainApplication.Companion.getContext().setVirtualKey(true);
                context.startActivity(launchIntentForPackage);
            }else {
                ToastUtils.Companion.showToast("打开第三方应用失败");
            }
        }catch (Exception e){}
    }

    public static void showWindows(FragmentActivity context, String packageName, String classPath) {
        //获取屏幕高宽
        DisplayMetrics metric = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int screenWidth = metric.widthPixels;
        int screenHeight = metric.heightPixels;

        Intent intent = new Intent();
        intent.setClassName(packageName,classPath);

        intent.setFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | Intent.FLAG_ACTIVITY_NEW_TASK);
        ActivityOptions activityOptions = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activityOptions = ActivityOptions.makeBasic();
        }

        //设置为freeform模式
        try {
            Method method = ActivityOptions.class.getMethod("setLaunchWindowingMode", int.class);
            method.invoke(activityOptions, WINDOWING_MODE_FREEFORM);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //freeform模式下自由窗口的大小
        int freeformWidth = 1080;
        int freeformHeight = 1920;
        //居中显示
        int left = screenWidth / 2 - freeformWidth / 2;
        int top = screenHeight / 2 - freeformHeight / 2;
        int right = screenWidth / 2 + freeformWidth / 2;
        int bottom = screenHeight / 2 + freeformHeight / 2;
        activityOptions.setLaunchBounds(new Rect(left, top, right, bottom));
        //activityOptions.setLaunchBounds(new Rect(0, 50, freeformWidth, freeformHeight));
        Bundle bundle = activityOptions.toBundle();
        context.startActivity(intent,bundle);
    }

    /**
     * 杀死除了 自身应用和将要打开的应用 以外的其他应用
     * @param mContext
     * @param openAppPackageName
     */
    public static void killOtherApp(Context mContext,String openAppPackageName){

        final String[] otheruncheckApp = {"deezer.android.app.nobilling"};

        ThreadUtil.getInstance().getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                ComponentName componentName = new ComponentName(MainApplication.Companion.getContext(), MainApplication.Companion.getContext().getClass());
                MediaSessionManager mSessionManager =  (MediaSessionManager) MainApplication.Companion.getContext().getSystemService(Context.MEDIA_SESSION_SERVICE);
                AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

                PackageManager localPackageManager = mContext.getPackageManager();
                List localList = localPackageManager.getInstalledPackages(0);
                for (int i = 0; i < localList.size(); i++) {
                    PackageInfo localPackageInfo1 = (PackageInfo) localList.get(i);
                    String packageName = localPackageInfo1.packageName.split(":")[0];
                    if (((ApplicationInfo.FLAG_SYSTEM & localPackageInfo1.applicationInfo.flags) == 0)
                            && ((ApplicationInfo.FLAG_UPDATED_SYSTEM_APP & localPackageInfo1.applicationInfo.flags) == 0)
                            && ((ApplicationInfo.FLAG_STOPPED & localPackageInfo1.applicationInfo.flags) == 0)) {
                        System.out.println("packageName =====> 进程应用: " + packageName);
                        if(packageName.equals(mContext.getPackageName())) {
                            continue;
                        }

                        if(packageName.equals(openAppPackageName)){
                            continue;
                        }

                        if("deezer.android.app.nobilling".equals(packageName)){
                            continue ;
                        }
                        if("com.doorbird.doorbird".equals(packageName)){
                            continue ;
                        }
                        //过滤正在播放音乐的应用
                        String musicActivePackgeName = "";
                        List<MediaController> controllers = mSessionManager.getActiveSessions(componentName);
                        for (MediaController mediaController : controllers){
                            if(mediaController.getPlaybackState() != null){
                                if(mediaController.getPlaybackState().getState() == PlaybackState.STATE_PLAYING){
                                    System.out.println("packageName =====> 正在播放音乐的应用: " +  mediaController.getPackageName());
                                    musicActivePackgeName = mediaController.getPackageName();
                                }
                            }
                        }
                        if(packageName.equals(musicActivePackgeName) && mAudioManager.isMusicActive()){
                            continue;
                        }

                        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
                        Method forceStopPackage = null;
                        try {
                            forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage", String.class);
                            forceStopPackage.setAccessible(true);
                            forceStopPackage.invoke(activityManager, packageName);
                            System.out.println("packageName =====> 杀死的应用: " + packageName);
                        } catch (NoSuchMethodException e) {
                            LogUtils.e("forceStopPackage NoSuchMethodException error = " + e.getMessage());
                        } catch (IllegalAccessException e) {
                            LogUtils.e("forceStopPackage IllegalAccessException error = " + e.getMessage());
                        } catch (InvocationTargetException e) {
                            LogUtils.e("forceStopPackage InvocationTargetException error = " + e.getMessage());
                        }
                    }
                }
            }
        });
    }

}